using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MouseKeyboardOperationSimulator
{
    /// <summary>
    /// 辅助函数类
    /// </summary>
    public static class HelperFunctions
    {
        // Win32 API声明
        [DllImport("user32.dll")]
        private static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

        [DllImport("user32.dll")]
        private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

        // 鼠标事件常量
        private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
        private const uint MOUSEEVENTF_LEFTUP = 0x0004;
        private const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
        private const uint MOUSEEVENTF_RIGHTUP = 0x0010;
        private const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
        private const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
        private const uint MOUSEEVENTF_WHEEL = 0x0800;
        private const uint MOUSEEVENTF_MOVE = 0x0001;

        // 键盘事件常量
        private const uint KEYEVENTF_KEYDOWN = 0x0000;
        private const uint KEYEVENTF_KEYUP = 0x0002;

        //#region Validation Methods

        /// <summary>
        /// 验证坐标格式 (x,y) - 不允许前导0
        /// </summary>
        public static bool ValidateCoordinateFormat(string content)
        {
            if (string.IsNullOrEmpty(content))
                return false;

            var parts = content.Split(',');
            if (parts.Length != 2)
                return false;

            // 使用ValidateIntegerFormat方法验证X和Y坐标，该方法已包含前导0检查
            return ValidateIntegerFormat(parts[0].Trim()) && ValidateIntegerFormat(parts[1].Trim());
        }

        /// <summary>
        /// 验证拖拽操作格式 (起始坐标;持续时间;结束坐标)
        /// </summary>
        public static bool ValidateDragOperationFormat(string content)
        {
            if (string.IsNullOrEmpty(content))
                return false;

            var segments = content.Split(';');
            if (segments.Length != 3)
                return false;

            var startCoordinate = segments[0].Trim();
            var duration = segments[1].Trim();
            var endCoordinate = segments[2].Trim();

            // 验证起始坐标格式
            if (!ValidateCoordinateFormat(startCoordinate))
                return false;

            // 验证持续时间格式（正整数）
            if (!ValidatePositiveIntegerFormat(duration))
                return false;

            // 验证结束坐标格式
            if (!ValidateCoordinateFormat(endCoordinate))
                return false;

            return true;
        }

        /// <summary>
        /// 验证整数格式（不允许前导0）
        /// </summary>
        public static bool ValidateIntegerFormat(string content)
        {
            if (string.IsNullOrEmpty(content))
                return false;

            // 检查是否包含前导0（正数：长度大于1且以0开头，负数：长度大于2且第二位为0）
            if (content.Length > 1)
            {
                // 对于负数，检查第二位是否为0
                if (content.StartsWith("-") && content.Length > 2 && content[1] == '0')
                    return false;
                // 对于正数，检查第一位是否为0
                else if (!content.StartsWith("-") && content[0] == '0')
                    return false;
            }

            // 尝试解析整数（包括负数）
            return int.TryParse(content, out _);
        }

        /// <summary>
        /// 验证正整数格式（不允许前导0）
        /// </summary>
        public static bool ValidatePositiveIntegerFormat(string content)
        {
            if (string.IsNullOrEmpty(content))
                return false;

            // 检查是否包含前导0（长度大于1且以0开头）
            if (content.Length > 1 && content[0] == '0')
                return false;

            // 尝试解析正整数
            if (int.TryParse(content, out int result))
            {
                return result > 0;
            }

            return false;
        }

        /// <summary>
        /// 验证按键格式 (只允许单个按键或标准组合键)
        /// </summary>
        public static bool ValidateKeyFormat(string content)
        {
            if (string.IsNullOrEmpty(content))
                return false;

            // 分割组合键
            var keys = content.Split('+');
            if (keys.Length > 3)
                return false; // 最多支持3个键的组合

            // 验证每个按键
            foreach (var key in keys)
            {
                if (!IsValidKey(key.Trim()))
                    return false;
            }

            return true;
        }

        /// <summary>
        /// 验证单个按键是否有效
        /// </summary>
        public static bool IsValidKey(string key)
        {
            // 使用.NET的Keys枚举来验证按键名称
            // 这会自动处理大部分标准按键
            try
            {
                // 特殊处理一些常见的按键名称
                switch (key.ToUpper())
                {
                    case "ENTER":
                        return true;
                    case "SPACE":
                        return true;
                    case "TAB":
                        return true;
                    case "BACKSPACE":
                        return true;
                    case "ESCAPE":
                    case "ESC":
                        return true;
                    case "CAPSLOCK":
                        return true;
                    case "NUMLOCK":
                        return true;
                    case "SCROLLLOCK":
                        return true;
                    case "PRINTSCREEN":
                        return true;
                    case "INSERT":
                        return true;
                    case "DELETE":
                    case "DEL":
                        return true;
                    case "HOME":
                        return true;
                    case "END":
                        return true;
                    case "PAGEUP":
                        return true;
                    case "PAGEDOWN":
                        return true;
                    case "UP":
                        return true;
                    case "DOWN":
                        return true;
                    case "LEFT":
                        return true;
                    case "RIGHT":
                        return true;
                }

                // 检查是否是功能键 (F1-F12)
                if (key.Length == 2 && key[0] == 'F' && char.IsDigit(key[1]))
                    return true;
                if (key.Length == 3 && key.StartsWith("F1") && char.IsDigit(key[2]) && key[2] <= '2')
                    return true;

                // 检查是否是数字键 (0-9)
                if (key.Length == 1 && char.IsDigit(key[0]))
                    return true;

                // 检查是否是字母键 (A-Z)，但排除汉字
                if (key.Length == 1 && char.IsLetter(key[0]))
                {
                    // 确保字符在ASCII范围内（英文字母），排除汉字等非ASCII字符
                    return key[0] <= 127;
                }

                // 使用Enum.TryParse检查是否是有效的Keys枚举值
                return Enum.TryParse(key, true, out Keys result);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 验证坐标字符串格式
        /// </summary>
        public static bool ValidateCoordinate(string coordinateStr)
        {
            if (string.IsNullOrEmpty(coordinateStr))
                return false;

            var parts = coordinateStr.Split(',');
            if (parts.Length != 2)
                return false;

            return int.TryParse(parts[0].Trim(), out _) && int.TryParse(parts[1].Trim(), out _);
        }

        //#endregion

        //#region Mouse Operations

        /// <summary>
        /// 设置鼠标坐标
        /// </summary>
        public static void SetMousePosition(int x, int y)
        {
            SetCursorPos(x, y);
        }

        /// <summary>
        /// 执行鼠标左键单击
        /// </summary>
        public static void MouseLeftClick(int x, int y)
        {
            SetMousePosition(x, y);
            mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
        }

        /// <summary>
        /// 执行鼠标左键拖动操作
        /// </summary>
        public static void MouseLeftDrag(int startX, int startY, int endX, int endY, int duration = 0)
        {
            // 移动到起始位置
            SetMousePosition(startX, startY);
            // 按下左键
            mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
            
            // 如果指定了拖动时长，则在移动过程中添加延迟
            if (duration > 0)
            {
                // 计算每毫秒移动的步长
                int steps = Math.Max(1, duration / 10); // 至少1步，每10毫秒一步
                int stepDelay = Math.Max(1, duration / steps);
                
                // 分步移动到目标位置
                for (int i = 1; i <= steps; i++)
                {
                    int currentX = startX + (endX - startX) * i / steps;
                    int currentY = startY + (endY - startY) * i / steps;
                    SetMousePosition(currentX, currentY);
                    System.Threading.Thread.Sleep(stepDelay);
                }
            }
            else
            {
                // 直接移动到结束位置
                SetMousePosition(endX, endY);
            }
            
            // 释放左键
            mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
        }

        /// <summary>
        /// 执行鼠标左键双击
        /// </summary>
        public static void MouseLeftDoubleClick(int x, int y)
        {
            MouseLeftClick(x, y);
            MouseLeftClick(x, y);
        }

        /// <summary>
        /// 执行鼠标右键单击
        /// </summary>
        public static void MouseRightClick(int x, int y)
        {
            SetMousePosition(x, y);
            mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
        }

        /// <summary>
        /// 执行鼠标右键双击
        /// </summary>
        public static void MouseRightDoubleClick(int x, int y)
        {
            MouseRightClick(x, y);
            MouseRightClick(x, y);
        }

        /// <summary>
        /// 执行鼠标中键单击
        /// </summary>
        public static void MouseMiddleClick(int x, int y)
        {
            SetMousePosition(x, y);
            mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
        }

        /// <summary>
        /// 执行鼠标滚轮操作
        /// </summary>
        /// <param name="delta">滚动的单位数，1表示向上滚动一下，-1表示向下滚动一下</param>
        public static void MouseWheel(int delta)
        {
            // 将用户友好的单位转换为API所需的WHEEL_DELTA单位
            // 1个单位 = 120 WHEEL_DELTA
            int apiDelta = delta * 120;
            // 将int转换为uint传递给mouse_event函数
            // 负数会自动转换为无符号整数的二进制补码形式
            mouse_event(MOUSEEVENTF_WHEEL, 0, 0, (uint)apiDelta, 0);
        }

        /// <summary>
        /// 执行键盘按键操作
        /// </summary>
        public static void KeyboardKeyPress(string key)
        {
            // 处理组合键
            if (key.Contains("+"))
            {
                string[] parts = key.Split('+');
                string modifier = parts[0].Trim().ToUpper();
                string keyCode = parts[1].Trim().ToUpper();

                // 按下修饰键
                Keys modifierKey = ParseKey(modifier);
                keybd_event((byte)modifierKey, 0, KEYEVENTF_KEYDOWN, 0);

                // 按下主键
                Keys mainKey = ParseKey(keyCode);
                keybd_event((byte)mainKey, 0, KEYEVENTF_KEYDOWN, 0);
                keybd_event((byte)mainKey, 0, KEYEVENTF_KEYUP, 0);

                // 释放修饰键
                keybd_event((byte)modifierKey, 0, KEYEVENTF_KEYUP, 0);
            }
            else
            {
                // 单个按键
                Keys parsedKey = ParseKey(key);
                keybd_event((byte)parsedKey, 0, KEYEVENTF_KEYDOWN, 0);
                keybd_event((byte)parsedKey, 0, KEYEVENTF_KEYUP, 0);
            }
        }

        /// <summary>
        /// 按下键盘按键
        /// </summary>
        public static void KeyboardKeyDown(string key)
        {
            Keys parsedKey = ParseKey(key);
            keybd_event((byte)parsedKey, 0, KEYEVENTF_KEYDOWN, 0);
        }

        /// <summary>
        /// 释放键盘按键
        /// </summary>
        public static void KeyboardKeyUp(string key)
        {
            Keys parsedKey = ParseKey(key);
            keybd_event((byte)parsedKey, 0, KEYEVENTF_KEYUP, 0);
        }

        /// <summary>
        /// 解析按键字符串为Keys枚举
        /// </summary>
        private static Keys ParseKey(string key)
        {
            // 处理特殊按键名称
            switch (key.ToUpper())
            {
                case "ENTER":
                    return Keys.Enter;
                case "SPACE":
                    return Keys.Space;
                case "TAB":
                    return Keys.Tab;
                case "BACKSPACE":
                    return Keys.Back;
                case "ESCAPE":
                case "ESC":
                    return Keys.Escape;
                case "CAPSLOCK":
                    return Keys.CapsLock;
                case "NUMLOCK":
                    return Keys.NumLock;
                case "SCROLLLOCK":
                    return Keys.Scroll;
                case "PRINTSCREEN":
                    return Keys.PrintScreen;
                case "INSERT":
                    return Keys.Insert;
                case "DELETE":
                case "DEL":
                    return Keys.Delete;
                case "HOME":
                    return Keys.Home;
                case "END":
                    return Keys.End;
                case "PAGEUP":
                    return Keys.PageUp;
                case "PAGEDOWN":
                    return Keys.PageDown;
                case "UP":
                    return Keys.Up;
                case "DOWN":
                    return Keys.Down;
                case "LEFT":
                    return Keys.Left;
                case "RIGHT":
                    return Keys.Right;
            }

            // 处理功能键
            if (key.Length >= 2 && key[0] == 'F' && int.TryParse(key.Substring(1), out int functionKeyNumber))
            {
                switch (functionKeyNumber)
                {
                    case 1: return Keys.F1;
                    case 2: return Keys.F2;
                    case 3: return Keys.F3;
                    case 4: return Keys.F4;
                    case 5: return Keys.F5;
                    case 6: return Keys.F6;
                    case 7: return Keys.F7;
                    case 8: return Keys.F8;
                    case 9: return Keys.F9;
                    case 10: return Keys.F10;
                    case 11: return Keys.F11;
                    case 12: return Keys.F12;
                }
            }

            // 尝试直接解析为Keys枚举
            if (Enum.TryParse(key, true, out Keys result))
            {
                return result;
            }

            // 默认返回空格键（避免异常）
            return Keys.Space;
        }

        //#endregion
    }
}